<template>
  <view class="img-box">
    <view v-for="(item, i) in files" class="img-item">
      <img
        @click="openPopup(item)"
        :src="formatSrc(item.fileUrl)"
        alt=""
        style="width: 15vw; height: 15vw"
      />
      <view class="delbtn" @click="del(i, item)"> X </view>
    </view>
    <view class="add-button" @click="onClick" v-if="files.length < limit">
      <uni-icons type="plusempty" style="color: aqua" size="30"></uni-icons>
    </view>
  </view>
  <!-- 普通弹窗 -->
  <uni-popup ref="popup" @change="changePopup" style="z-index: 999">
    <img
      :src="formatSrc(showImgUrl)"
      alt=""
      style="width: 80vw; max-height: 80vh"
    />
    <button type="primary" @click="onDownLoad" style="display: block">
      下载
    </button>
  </uni-popup>
</template>

<script setup>
import { useAuthStore } from "@/store/modules/auth.js";
import { ref, defineProps, defineEmits, watch } from "vue";
import { BASE_URL } from "@/utils/requset.js";
import { BASE_FILE_URL } from "@/utils/requset.js";
import { formatSrc } from "@/utils/index.js";
const props = defineProps({
  modelValue: [String, Object, Array],
  // 数量限制
  limit: {
    type: Number,
    default: 5,
  },
});
const emits = defineEmits(["update:modelValue", "change"]);
const authStore = useAuthStore();
const token = authStore.getToken;
const fileNum = ref(0);
const files = ref([]);
const onClick = () => {
  uni.chooseImage({
    count: 6, //默认9
    sizeType: ["original", "compressed"], //可以指定是原图还是压缩图，默认二者都有
    sourceType: ["album", "camera"], //album 从相册选图，camera 使用相机
    success: function (res) {
      const { tempFilePaths, tempFiles } = res;
      uni.uploadFile({
        url: BASE_URL + "/file/upload", //服务器地址服务器地址
        fileType: tempFiles[0].type, //ZFB必填,不然报错
        filePath: tempFilePaths[0], //这个就是我们上面拍照返回或者先中照片返回的数组
        name: "file",
        header: {
          Authorization: `Bearer ${token}`,
        },
        success: (uploadFileRes) => {
          const { data } = uploadFileRes;
          const res = JSON.parse(data);
          const { code, msg } = res;
          if (code !== 200) {
            uni.showToast({
              title: msg,
              icon: "error",
            });
            return false;
          }
          files.value.push(res.data);
          emits("update:modelValue", files.value);
          emits("change", files.value);
        },
      });
    },
  });
};
const del = (index, file) => {
  files.value.splice(index, 1);
  emits("update:modelValue", files.value);
  emits("change", files.value);
};
const popup = ref();
const showImgUrl = ref("");
const isOpen = ref(false);

const openPopup = (item) => {
  if (isOpen.value) {
    popup.value.close();
  } else {
    showImgUrl.value = item.fileUrl;
    popup.value.open("center");
  }
  isOpen.value = !isOpen.value;
};
const changePopup = (e) => {
  isOpen.value = e.show;
};
watch(
  () => props.modelValue,
  (val) => {
    if (val) {
      let list = val || [];
      files.value = list.filter((item) => item != null);
    } else {
      files.value = [];
    }
    fileNum.value = files.value.length;
  },
  { deep: true, immediate: true }
);
function onDownLoad(item) {
  let url = formatSrc(showImgUrl.value);
  let filename = "隐患图片.png";
  uni.showLoading({
    title: "正在下载",
  });

  let dtask = plus.downloader.createDownload(
    url,
    {
      filename: filename, //利用保存路径，实现下载文件的重命名
    },
    (d, status) => {
      //d为下载的文件对象
      if (status == 200) {
        let fileSaveUrl = plus.io.convertLocalFileSystemURL(d.filename);

        uni.hideLoading();
        uni.showToast({
          icon: "none",
          mask: true,
          title: "已保存到" + fileSaveUrl, //保存路径
          duration: 3000,
        });
        //下载成功,d.filename是文件在保存在本地的相对路径，使用下面的API可转为平台绝对路径
        // plus.runtime.openFile(d.filename); //选择软件打开文件
      } else {
        //下载失败
        uni.hideLoading();
        plus.downloader.clear(); //清除下载任务
        uni.showToast({
          icon: "none",
          mask: true,
          title: "下载失败，请稍后重试",
        });
      }
    }
  );
  dtask.start();
}
</script>

<style lang="scss" scoped>
.img-box {
  width: 100vw;
  height: 12vw;
  display: flex;

  .img-item {
    position: relative;
    margin-right: 25upx;
  }
  .delbtn {
    position: absolute;
    top: -20upx;
    right: -20upx;
    z-index: 2;
    width: 30upx;
    height: 30upx;
    border-radius: 50%;
    background-color: #fff;
    text-align: center;
    line-height: 30upx;
    border: #ccc 1px solid;
  }
}

.add-button {
  width: 15vw;
  height: 15vw;
  border: 1px solid aqua;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
}
</style>
